<?php

namespace app\admin\controller\user;

use app\admin\model\Order;
use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->where(['type'=>1])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->jrxz  = Order::where(['user_id'=>$v->id])->whereTime('createtime', 'd')->count();//进入新增
                $v->yiwancheng  = Order::where(['order_status'=>5,'user_id'=>$v->id])->count();//已完成
                $v->daichuli    = Order::where(['order_status'=>3,'user_id'=>$v->id])->count();//代处理
                $v->daishouhuo  = Order::where(['order_status'=>2,'user_id'=>$v->id])->count();//待收货
                $v->daijiesuan  = Order::where(['order_status'=>4,'user_id'=>$v->id])->count();//待结算
                $v->shibai      = Order::where(['order_status'=>0,'user_id'=>$v->id])->count();//失败

            }
            $zong_money =  $this->model
                ->with('group')
                ->where($where)
                ->where(['type'=>1])->sum('money');
            $result = array("total" => $list->total(), "rows" => $list->items(),'zong_money'=>$zong_money);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查看
     */
    public function indextwo()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $ids = \app\admin\model\user\Agency::column('user_id');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where(['type'=>2])
                ->whereNotIn('id', $ids)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['salt']      = Random::alnum();
        $params['status']    = 'normal';
        $params['password']  = $this->getEncryptPassword($params['password'], $params['salt']);;
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public function pwd($ids)
    {
        $row = $this->model->get($ids);
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
//        $params['password']  = $this->getEncryptPassword($params['password'], $row['salt']);
//        dump($params['password'] );exit();
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
            $row = $this->model->get($ids);
            $this->modelValidate = true;
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($params['money'] == 0){
            $this->error('请输入正确的金额');
        }
        $UserModel = new \app\common\model\User();
        $agencyModel = new \app\admin\model\user\Agency();
        $agencyInfo  = $agencyModel->where(['user_id'=>$ids])->find();
        if($agencyInfo){
            if($agencyInfo->type == 1){
                $money = config('site.plot_money')+config('site.hou_plot_money');
            }else{
                $money = config('site.county_money')+config('site.hou_county_money');;
            }
            if($agencyInfo->money <= $money){
                $jieyu_money = bcadd($agencyInfo->money,$params['money']);
                if($jieyu_money == $money){
                    $agencyInfo->money +=$params['money'];
                    $agencyInfo->save();
                    $this->success();
                }else if($jieyu_money < $money){
                    $agencyInfo->money = $jieyu_money;
                    $agencyInfo->save();
                    $this->success();
                }else if($jieyu_money > $money){
                    $agencyInfo->money = $money;
                    $agencyInfo->save();
                    $params['money'] = $jieyu_money-$money;
                }
            }
        }
        $UserModel->money($params['money'],$ids,$params['memo']);
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        if($ids == '137' || $ids == '39'){
            $this->error(__("不能删除该用户"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

}
